package cn.lijiguo.concurrency.part1.ch05;

import java.time.Duration;
import java.time.Instant;

/**
 * ThreadJoin3
 *
 * @author lijiguo
 * @date 2019/12/13 13:30
 */
public class ThreadJoin3 {

    public static void main(String[] args) throws InterruptedException {
        Instant start = Instant.now();

        Thread t1 = new Thread(new CaptureRunnable("machine1", 100L));
        Thread t2 = new Thread(new CaptureRunnable("machine2", 300L));
        Thread t3 = new Thread(new CaptureRunnable("machine3", 500L));

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        Instant end = Instant.now();
        long millis = Duration.between(start, end).toMillis();
        System.out.printf("总共执行: %d 毫秒\n", millis);
    }
}

class CaptureRunnable implements Runnable {

    private String machineName;

    private long mills;

    public CaptureRunnable(String machineName, long mills) {
        this.machineName = machineName;
        this.mills = mills;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 获取执行结果
        String result = getResult();
        System.out.println(Thread.currentThread().getName() + ":" + result);
    }

    public String getResult() {
        return machineName + " finish.";
    }
}